package org.penguin.boot.security.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.penguin.boot.security.entity.PenguinUserDetails;
import org.penguin.boot.security.entity.User;

import org.penguin.boot.security.service.UserService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.Optional;

@Slf4j
@Transactional
@Service("userDetailsService")
public class PenguinUserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserService userService;

    @Override
    public PenguinUserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        if (StringUtils.isEmpty(email)) {
            throw new UsernameNotFoundException("用户名不能为空！");
        }
        Optional<User> userOptional = userService.findByEmail(email);
        return new PenguinUserDetails(userOptional.orElseThrow(() -> new UsernameNotFoundException(String.format("找不到用户: %s", email))));
    }
}
